<?php

namespace App\Modules\Advertisement\Model;

use Illuminate\Database\Eloquent\Model;
use Cache;


class AdModel extends Model
{
    protected $table = 'ad';
    protected $fillable =
        [   'id',
            'target_id',
            'ad_type',
            'ad_position',
            'ad_name',
            'ad_file',
            'ad_content',
            'ad_url',
            'start_time',
            'end_time',
            'uid',
            'username',
            'listorder',
            'is_open',
            'created_at'
        ];
    public  $timestamps = false;

    static function getAdByCode($code)
    {
        $banners = [];
        if(Cache::has('ad_'.$code))
        {
            $banners = Cache::get('ad_'.$code);
        }
        else
        {
            $ad_target = AdTargetModel::select('target_id')->where('code' , $code)->first();
            if(!empty($ad_target))
            {
                $banners = AdModel::where('target_id', $ad_target->target_id)->where(function($where){
                    $where->where('ad.end_time','0000-00-00 00:00:00')
                        ->orWhere('ad.end_time','>',date('Y-m-d h:i:s',time()));
                })->get();
                $banners = empty($banners)? []: $banners->toArray();
            }
            Cache::put('ad_'.$code, $banners, 60*24);
        }

        return $banners;
    }

    static function getOpenAd()
    {
        $results = self::where('is_open',1)->select('ad_file')->get();
        if ($results) {
            $results = $results->toArray();
        }
        return $results;
    }

}
